# file:: telnet_reporter.rb
# author::  Ralph M. Churchill
# version::
# date::
#
# This source code copyright (C) 2006 by Ralph M. Churchill
# All rights reserved.
#
# Released under the terms of the GNU General Public License
# See LICENSE file for additional information.

require 'engine/logic'
require 'models/character'

# Though it is Logic, it overrides the core method, do_action.
class TelnetReporter < Logic
    applicable_to Character
    stackable :replaceable

    def initialize(player,connection)
        @connection = connection
        self.owner = player
    end
    
    def do_action(action)
        case action.type
        when :say
            speaker = (action.performer==self.owner) ? 'You say' :
                "#{TelnetCommands::BOLD+action.performer.name+TelnetCommands::RESET} says"
            @connection.display("#{speaker} \"#{action.data[:msg]}\"")
        when :see
            what = action.data[:target]
            @connection.display(erb_evaluate(what))
        when :vision
            @connection.display(action.data[:sight].gsub(self.owner.name,'You'))
        when :enterroom,:leaveroom
            @connection.display(enter_or_leave_room(action)) \
                unless action.performer == self.owner
        when :leave
            @connection.del_handler
        when :error,:announce
            @connection.display(action.data[:msg])
        end
        true
    end
private
    def enter_or_leave_room(action)
        who = action.performer
        room,portal = action.data[:room],action.data[:portal]

        if portal then
            verb = (action.type == :enterroom) ? \
                "enters from" : "leaves through"
            "#{who} #{verb} #{portal}"
        else
            verb = (action.type == :enterroom) ? \
                "appears from nowhere!" : "vanishes..."
            "#{who} #{verb}"
        end
    end
    def erb_evaluate(what)
        require 'erb'
        what.extend TelnetERB
        edoc = ERB.new(what.describe)
        doc2 = edoc.result(what.get_binding)
        # ugh. a hack for descriptions that include erb descriptions
        edoc2 = ERB.new(doc2)
        edoc2.result(what.get_binding)
    end
end

module TelnetERB
    def concat(string, binding)
        eval("_erbout", binding).concat(string)
    end
    TelnetCommands.constants.each do |cmd|
        module_eval <<-"end_eval"
            def #{cmd.downcase}(&blk)
                concat(\"#{TelnetCommands.const_get(cmd)}\",blk.binding)
                yield
                concat(\"#{TelnetCommands::RESET}\",blk.binding)
            end
        end_eval
    end
end
